<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-card shadow="hover" class="layout-padding-auto create-form">
			<el-form ref="formRef" :model="stateData.vmModel" label-width="120px">
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>单据信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_BillCode_FormItem" prop="Entity.BillCode">
								<template #label>
									<WtmLabelTooltip label="单据编号" tooltip="单编号" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.BillCode" clearable class="width100" disabled placeholder="自动生成"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Remark_FormItem" prop="Entity.Remark">
								<template #label>
									<WtmLabelTooltip label="备注" tooltip="备注" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Remark" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>工作信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<WtmOrgSelector
								v-model="stateData.vmModel.Entity.OrgId"
								label="公司"
								:auth="true"
								:rules="[{ required: true, message: '公司为必填项', trigger: 'blur' }]"
							/>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<WtmDeptSelector v-model="stateData.vmModel.Entity.GroupId" label="所属部门" :auth="true" :org-id="stateData.vmModel.Entity.OrgId" />
						</el-col>
					</el-row>
				</div>
				<div class="form-section" v-if="stateData.vmModel.Entity.ID">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>岗位分配明细</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="24" class="mb20">
							<SysHrJobAssignmentRequestBillEntry
								:search-bar="false"
								:toolbar="true"
								:is-disabled="true"
								:entity-id="stateData.vmModel.Entity.ID"
								:group-id="stateData.vmModel.Entity.GroupId"
								:org-id="stateData.vmModel.Entity.OrgId"
							/>
						</el-col>
					</el-row>
				</div>
			</el-form>
		</el-card>
	</div>
</template>

<script setup lang="ts" name="message._system.common.vm.edit;false">
import ElMessage from 'element-plus/es/components/message/index';
import { reactive, ref, getCurrentInstance, onMounted, nextTick, computed, defineAsyncComponent, type ComponentInternalInstance } from 'vue';
import { SysHrJobAssignmentRequestBillApi as api } from '/@/views/hr/syshrjobassignmentrequestbill/api';
import other from '/@/utils/other';
import { useRouter } from 'vue-router';
import { ISysHrJobAssignmentRequestBillVm } from '/@/views/hr/syshrjobassignmentrequestbill/api/interface';
import { IViewModel } from '/@/types/common';

// 懒加载子组件
const SysHrJobAssignmentRequestBillEntry = defineAsyncComponent(() => import('/@/views/hr/syshrjobassignmentrequestbillentry/index.vue'));

// 常量定义
const BILL_STATUS = {
	DRAFT: '草稿',
	IN_AUDIT: '审核中',
} as const;

const WORKFLOW_STATUS = {
	PENDING: '待提交',
	SUBMITTING: '提交中',
	IN_AUDIT: '审核中',
} as const;

const BUTTON_TEXTS = {
	SAVE: '保存',
	SUBMIT: '提交',
	AGREE: '提交',
	REJECT: '取消',
	CLOSE: '关闭',
} as const;

const ACTIONS = {
	AGREE: '同意',
	REJECT: '拒绝',
} as const;

const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();
const activeTab = ref('main');

// 初始化表单数据
const stateData = reactive<IViewModel<ISysHrJobAssignmentRequestBillVm>>({
	vmModel: {
		Entity: {
			ID: null,
			Approver: null,
			ApprovalTime: null,
			ApprovalOpinion: null,
			GroupId: null,
			OrgId: null,
			BillCode: null,
			BillStatus: null,
			WorkflowStatus: null,
			Remark: null,
		},
		ActionName: null,
		IsMyApprove: null,
		Remark: null,
	},
	AllSysGroups: [],
});

// 计算属性
const isInAudit = computed(() => stateData.vmModel.Entity.WorkflowStatus === WORKFLOW_STATUS.IN_AUDIT);
const canSubmit = computed(() => stateData.vmModel.Entity.BillStatus === BILL_STATUS.DRAFT);
const canApprove = computed(() => !!stateData.vmModel.IsMyApprove);

// 统一的成功处理函数
const handleSuccess = (isSubmit = false) => {
	// 根据操作类型显示不同的消息
	if (isSubmit) {
		ElMessage.success(ci.proxy?.$t('message._system.common.vm.submittip') || '提交成功');
		emit('refresh');
		closeDialog();
	} else {
		ElMessage.success(ci.proxy?.$t('message._system.common.vm.savetip') || '保存成功');
		emit('refresh');
		// 保存后不关闭弹窗
	}
	loading.value = false;
};

// 统一的错误处理函数
const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

// 公共的API请求处理函数
const handleApiRequest = (apiCall: () => Promise<any>, isSubmit = false) => {
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			loading.value = true;
			apiCall()
				.then(() => handleSuccess(isSubmit))
				.catch(handleError);
		}
	});
};

// 公共的审批处理函数
const handleApproval = (actionName: string) => {
	stateData.vmModel.ActionName = actionName;
	loading.value = true;
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			api()
				.approve(stateData.vmModel, '')
				.then(() => handleSuccess(true))
				.catch(handleError);
		} else {
			loading.value = false;
		}
	});
};

// 取消
const onClose = () => {
	closeDialog();
};

// 保存
const onSave = () => {
	handleApiRequest(() => api().edit(stateData.vmModel), false); // 保存后不关闭弹窗
};

// 提交
const onSubmit = () => {
	if (!stateData.vmModel.Entity.WorkflowStatus || stateData.vmModel.Entity.WorkflowStatus === WORKFLOW_STATUS.PENDING) {
		stateData.vmModel.Entity.WorkflowStatus = WORKFLOW_STATUS.SUBMITTING;
	}
	handleApiRequest(() => api().edit(stateData.vmModel), true); // 提交后关闭弹窗
};

// 同意
const onAgree = () => {
	handleApproval(ACTIONS.AGREE);
};

// 拒绝
const onDeny = () => {
	handleApproval(ACTIONS.REJECT);
};

// 初始化页面数据
const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	const routeId = useRouter().currentRoute.value.query.id;

	if (wtmdata?.ID) {
		stateData.vmModel.Entity.ID = wtmdata.ID;
	} else if (routeId) {
		stateData.vmModel.Entity.ID = routeId as any;
	}
};

// 加载页面数据
const loadPageData = async () => {
	try {
		// 先加载选择列表数据，确保组织选择器的选项已加载
		// 这样可以避免组织ID回显显示问题
		await loadSelectListData();

		// 再加载实体数据
		const response = await api().get(stateData.vmModel.Entity.ID ?? '');
		other.setValue(stateData.vmModel, response);
	} catch (error) {
		console.error('加载数据失败:', error);
		throw error;
	}
};

// 加载选择列表数据
const loadSelectListData = async () => {
	// 这里暂时为空，但为了保持一致性和未来扩展性而保留
	// 组织选择器会自动加载其所需的数据
};

// 页面加载时
onMounted(async () => {
	loading.value = true;
	initializePageData();

	try {
		await loadPageData();
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

// 设置对话框头部按钮
const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.SAVE,
			type: undefined,
			onClick: onSave,
			visible: !isInAudit.value, // 非审批状态时显示保存按钮
		},
		{
			text: BUTTON_TEXTS.SUBMIT,
			confirm: '提交单据以后无法修改，是否确认提交?',
			type: 'primary',
			onClick: onSubmit,
			visible: canSubmit.value && !isInAudit.value, // 草稿状态且非审批时显示提交
		},
		{
			text: BUTTON_TEXTS.SUBMIT,
			type: 'primary',
			onClick: onAgree,
			visible: isInAudit.value && canApprove.value, // 审批状态且有审批权限时显示同意
		},
		{
			text: BUTTON_TEXTS.REJECT,
			type: 'danger',
			onClick: onDeny,
			visible: isInAudit.value && canApprove.value, // 审批状态且有审批权限时显示拒绝
		},
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];

	emit('updateHeaderButtons', headerButtons);
};
</script>
